package com.wms.controller;

import com.wms.service.OutConfirmService;
import com.wms.service.StockConfirmService;
import com.mes.entity.User;
import com.yy.base.page.Message;
import com.yy.base.util.SessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 备料确认
 */
@Controller
@RequestMapping(value = "/outConfirm")
public class OutConfirmController {
	@Autowired
	private StockConfirmService stockConfirmService;
	@Autowired
	private OutConfirmService outConfirm;
	
	@ResponseBody
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public Message search(String ckd) throws IOException {
		Message message = new Message();
		if (ckd == null || "".equals(ckd)) {
			message.setErrorMessage("出库单不能为空");
			return message;
		}
		ckd = ckd.trim();
		
		Map<String, Object> orderInfo = stockConfirmService.getOutCodebyInfo(ckd);
		if (orderInfo == null) {
			message.setErrorMessage("出库单号不正确！");
			return message;
		}
		List<Map<String, Object>> list = outConfirm.getOrderOutList(ckd);
		if (list != null && list.isEmpty()) {
			message.setErrorMessage("此出库单已出库！");
			return message;
		}
		
		message.setData("list", list);
		message.setOkMessage("ok");
		return message;
	}
	
	@ResponseBody
	@Transactional(rollbackFor= Exception.class)
	@RequestMapping(value = "/outStorage", method = RequestMethod.POST)
	public Message outStorage(String code, @RequestParam(value = "ids") String ids,
							  @RequestParam(value = "qtys") String qtys, HttpServletRequest request) throws IOException {

		String[] outIds = ids.split(",");
		String[] outQtys = qtys.split(",");
		Message message = new Message();
		if (code == null || "".equals(code)) {
			message.setErrorMessage("出库单不能为空");
			return message;
		}
		if (ids == null) {
			message.setErrorMessage("未接收到数量信息！");
			return message;
		}
		Map<String, Object> orderInfo = stockConfirmService.getOutCodebyInfo(code);
		if (orderInfo == null) {
			message.setErrorMessage("出库单号不正确！");
			return message;
		}
		List<Map<String, Object>> list = outConfirm.getOrderOutList(code);
		if (list != null && list.isEmpty()) {
			message.setErrorMessage("此出库单已出库！");
			return message;
		}
		User user = SessionInfo.getUser();
		String error = outConfirm.outStorageConfirm(list, outIds, outQtys, user);
		if (error != null) {
			throw new RuntimeException(error);
		} else {
			message.setOkMessage("出库成功！");
		}
		return message;
	}
}